package com.baohua.service.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.stereotype.Service;

import com.baohua.dao.StaffDao;
import com.baohua.exception.BaohuaSystemException;
import com.baohua.model.Role;
import com.baohua.model.Staff;
import com.baohua.service.RoleService;
import com.baohua.service.StaffService;
import com.baohua.util.BeanUtils;
import com.baohua.util.ExcelUtil;

@Service("staffService")
public class StaffServiceImpl implements StaffService {

	/**
	 * 根据条件查询员工列表
	 * @param staff 员工对象
	 * @param pre_employDate  前置入职时间
	 * @param af_employDate 后置入职时间
	 * @param pre_leaveDate 前置离职时间
	 * @param af_leaveDate 后置离职时间
	 * @param active 是否有效
	 * @param sex 性别
	 * @param page
	 * @param pageSize
	 * @return
	 */
	@Override
	public Map queryStaff(Staff staff, String pre_employDate,
			String af_employDate, String pre_leaveDate, String af_leaveDate,
			String active, String sex, int page, int pageSize) {
		Map map = new HashMap();
		StringBuffer sqlCount = new StringBuffer("select count(*) from Staff s where 1=1");;
		StringBuffer sql = new StringBuffer("from Staff s where 1=1");
		
	//拼接SQL
		
		if(!StringUtils.isEmpty(staff.getStaffNO())) {
			sql.append(" and s.staffNO = '" + staff.getStaffNO() + "'");
			sqlCount.append(" and s.staffNO = '" + staff.getStaffNO() + "'");
		}
		if(!StringUtils.isEmpty(staff.getStaffName())) {
			sql.append(" and s.staffName = '" + staff.getStaffName() + "'");
			sqlCount.append(" and s.staffName = '" + staff.getStaffName() + "'");
		}
		if(!StringUtils.isEmpty(pre_employDate)) {
			sql.append(" and s.employDate >= '" + pre_employDate + "'");
			sqlCount.append(" and s.employDate >= '" + pre_employDate + "'");
		}
		
		if(!StringUtils.isEmpty(af_employDate)) {
			sql.append(" and s.employDate <= '" + af_employDate + "'");
			sqlCount.append(" and s.employDate <= '" + af_employDate + "'");
		}
		
		if(!StringUtils.equals(staff.getDeptId(), "0")&&!StringUtils.isEmpty(staff.getDeptId())) {
			sql.append(" and s.deptId = '" + staff.getDeptId() + "'");
			sqlCount.append(" and s.deptId = '" + staff.getDeptId() + "'");
		}
		
		if(!StringUtils.isEmpty(pre_leaveDate)) {
			sql.append(" and s.leaveDate >= '" + pre_leaveDate + "'");
			sqlCount.append(" and s.leaveDate >= '" + pre_leaveDate + "'");
		}
		
		if(!StringUtils.isEmpty(af_leaveDate)) {
			sql.append(" and s.leaveDate <= '" + af_leaveDate + "'");
			sqlCount.append(" and s.leaveDate <= '" + af_leaveDate + "'");
		}
		
		if(!StringUtils.isEmpty(staff.getPosition())) {
			sql.append(" and s.position = '" + staff.getPosition() + "'");
			sqlCount.append(" and s.position = '" + staff.getPosition() + "'");
		}
		if(!StringUtils.isEmpty(active)) {
			sql.append(" and s.active = '" + active + "'");
			sqlCount.append(" and s.active = '" + active + "'");
		}
		
		if(!StringUtils.isEmpty(active)) {
			sql.append(" and s.active = '" + active + "'");
			sqlCount.append(" and s.active = '" + active + "'");
		}
		
		if(!StringUtils.isEmpty(sex)) {
			sql.append(" and s.sex = '" + sex + "'");
			sqlCount.append(" and s.sex = '" + sex + "'");
		}
		
		
		List<Staff> list = staffDao.queryStaff(sql.toString(),(page-1)*pageSize, pageSize);
		long count = staffDao.countStaff(sqlCount.toString());
		map.put("Rows", list);
		map.put("Total", count);
		return map;
	}


	/**
	 * 根据员工编号查询员工
	 * @param staffNo
	 * @return
	 */
	@Override
	public Staff queryStaffByStaffNo(String staffNo) throws BaohuaSystemException {
		if(staffNo == null) {
			throw new BaohuaSystemException("员工编号不能为空");
		}
		Staff staff = staffDao.queryStaffByStaffNo(staffNo);
		return staff;
	}

	/**
	 * 增加员工
	 * @param staff
	 * @param employee
	 * @param roles
	 * @throws BaohuaSystemException
	 * @throws ParseException
	 */
	@Override
	public void addStaff(Staff staff, String employee, String[] roleIds) throws BaohuaSystemException, ParseException {
		Staff s = staffDao.queryStaffByStaffNo(staff.getStaffNO());
		if(s == null) {
		    String password = staff.getPassword();
	//1.CreateTime为DateTime类型
			    Timestamp createTime = new Timestamp(new Date().getTime());
	//2.处理入职日期
			    Date employDate = null;
			    if(!StringUtils.isBlank(employee)){
			    	employDate = DateUtils.parseDate(employee, new String[]{"yyyy-MM-dd"});
			    }
	//2.对密码进行MD5不可逆加密
			    String jPassword = DigestUtils.md5Hex(password);
	//3.对传过来的RoleId进行处理
			    if(roleIds!=null && roleIds.length>0) {
			    	Set<Role> roles = new HashSet<Role>();
				    for(String roleId : roleIds) {
				    	int id = Integer.parseInt(roleId);
							Role role = roleService.queryRoleById(id);
							roles.add(role);
							staff.setRoles(roles);
					}
			    }
	//对staff进行设置		    
			    staff.setCreateTime(createTime);
			    staff.setPassword(jPassword);
			    staff.setEmployDate(employDate);
			   
			    staffDao.addStaff(staff);
		}else{
			throw new BaohuaSystemException("员工已经存在");
		}
	}

	/**
	 * 根据ID删除员工
	 * @param staffId
	 * @throws BaohuaSystemException
	 */
	@Override
	public void delStaff(int staffId) throws BaohuaSystemException {
		Staff s = staffDao.queryStaffByStaffId(staffId);
		if(s!=null) {
			staffDao.delStaff(s);
		}else {
			throw new BaohuaSystemException("此员工不存在");
		}
	}

	/**
	 * 修改员工
	 * @param staff
	 * @throws BaohuaSystemException
	 */
	@Override
	public void updateStaff(Staff staff) throws BaohuaSystemException {
			Staff s = staffDao.queryStaffByStaffId(staff.getStaffId());
			if(s!=null) {
				if(!BeanUtils.compareObject(s, staff)) {
					BeanUtils.copyProperty(staff, s);
					//BeanUtils不拷贝集合类
					s.setRoles(staff.getRoles());
					staffDao.updateStaff(s);
			   }
		}else {
			throw new BaohuaSystemException("此员工已经存在");
		}
	}

	/**
	 * 员工登录
	 * @param username
	 * @param password
	 * @return
	 */
	@Override
	public Staff loginStaff(String username, String password) {
		return null;
	}

	/**
	 * 根据HQL语句统计员工
	 * @param sql
	 * @return
	 */
	@Override
	public long countStaff(String sql) {
		return staffDao.countStaff(sql);
	}

	/**
	 * 根据员工Id进行查询
	 * @param staffId
	 * @return
	 * @throws BaohuaSystemException
	 */
	@Override
	public Staff queryStaffById(int staffId) throws BaohuaSystemException {
		Staff r = staffDao.queryStaffByStaffId(staffId);
		return r;
	}

	/**
	 * 根据员工ID进行查询员工角色，将角色ID加入到List中
	 * @param staffId
	 * @return
	 * @throws BaohuaSystemException
	 */
	@Override
	public List<Integer> queryRolesById(int staffId)
			throws BaohuaSystemException {
		List<Integer> list = new ArrayList<Integer>();
		List<Role> roles = staffDao.queryRolesByStaffId(staffId);
		for(Role role : roles) {
			list.add(role.getRoleId());
		}
		return list;
	}
	
	/**
	 * 根据员工ID的数组, 查询员工列表
	 * @param staffNOs
	 * @return
	 */
	@Override
	public List<Staff> queryByStaffNOs(String[] staffNOs) {
		List<Staff> list = new ArrayList<Staff>();
		if(staffNOs.length!=0) {
		  list = staffDao.queryByStaffNOs(staffNOs);
		}
		return list;
	}
	
	public void exportData(String fileName, List list, String sheetName,
			 HttpServletRequest request, HttpServletResponse response)
					 throws IllegalArgumentException, 
			 IOException, IllegalAccessException {
		InputStream bis = null;
		OutputStream bos = null;
		OutputStream output = null;
		ExcelUtil<Staff> excelUtil = new ExcelUtil<Staff>(Staff.class);
		File file = new File(fileName);
		response.setContentType("application/x-msdownload;"); 
		output = new BufferedOutputStream(new FileOutputStream(file));
		if(list.size()==0) {
			excelUtil.exportExcel(list, sheetName, true, output);
		}else {
			excelUtil.exportExcel(list, sheetName, false, output);
		}
		 
		String agent = request.getHeader("USER-AGENT");
		if (null != agent && -1 != agent.indexOf("MSIE")){//IE
		// 设置文件头，文件名称或编码格式
		   response.setHeader("Content-Disposition", "attachment;filename="
		           + java.net.URLEncoder.encode(file.getName(), "UTF-8"));
		}else{//firefox
			response.setHeader("Content-disposition", "attachment; filename="  
	                + new String(file.getName().getBytes("utf-8"), "ISO8859-1"));
		}
       response.setHeader("Content-Length", String.valueOf(file.length()));
		
			bis = new BufferedInputStream(new FileInputStream(file));  
           bos = new BufferedOutputStream(response.getOutputStream());  
           byte[] buff = new byte[2048];  
           int bytesRead;  
           while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
               bos.write(buff, 0, bytesRead); 
           }
           if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
	}
	
	
	
   private StaffDao staffDao;
   private RoleService roleService;
   
	public RoleService getRoleService() {
	   return roleService;
	}


	@Resource(name="roleService")
	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	public StaffDao getStaffDao() {
		return staffDao;
	}

	@Resource(name="staffDao")
	public void setStaffDao(StaffDao staffDao) {
		this.staffDao = staffDao;
	}

}
